package com.dwd.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dwd.hrm.client.CourseDocClient;
import com.dwd.hrm.config.RabbitMQConfig;
import com.dwd.hrm.doc.CourseDoc;
import com.dwd.hrm.domain.Course;
import com.dwd.hrm.domain.CourseDetail;
import com.dwd.hrm.domain.CourseMarket;
import com.dwd.hrm.domain.CourseType;
import com.dwd.hrm.dto.CourseDto;
import com.dwd.hrm.enums.CourseGrade;
import com.dwd.hrm.mapper.*;
import com.dwd.hrm.query.CourseDocQuery;
import com.dwd.hrm.service.ICourseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dwd.hrm.util.AjaxResult;
import com.dwd.hrm.util.PageList;
import com.dwd.hrm.util.UserContextHolder;
import com.dwd.hrm.utils.ValidUtils;
import com.dwd.hrm.vo.UserContext;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wendi
 * @since 2021-03-05
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseResourceMapper courseResourceMapper;
    @Autowired
    private CourseDocClient courseDocClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean deleteById(Serializable id) {
        //基本信息
        courseMapper.deleteById(id);
        //市场信息
        courseMarketMapper.deleteById(id);
        //详情信息
        courseDetailMapper.deleteById(id);
        //资源信息
//        courseResourceMapper.deleteByCourseId(id);
        return true;
    }

    @Override
    public void updateById(CourseDto courseDto) {
        courseMapper.updateById(courseDto.getCourse());
        courseDto.getCourseDetail().setId(courseDto.getCourse().getId());
        courseDetailMapper.updateById(courseDto.getCourseDetail());
        courseDto.getCourseMarket().setId(courseDto.getCourse().getId());
        courseMarketMapper.updateById(courseDto.getCourseMarket());
    }

    @Override
    public void insert(CourseDto courseDto) {
        //返回自增id
        Course course = courseDto.getCourse();
        //校验
        ValidUtils.assertNotNull(course.getGradeId(), "不能为空");
        //设置等级
        CourseGrade courseGrade = CourseGrade.GetGrade(Integer.valueOf(courseDto.getCourse().getGradeId().toString()));
        course.setGradeName(courseGrade.getGradeName());
        //上下文获取用户的id和机构id，名字

        UserContext userContext = UserContextHolder.get();
        course.setUserId(userContext.getUserId());
        course.setUserName(userContext.getUserName());
        course.setTenantId(userContext.getTenantId());
        course.setTenantName(userContext.getTenantName());

        courseMapper.insert(course);
        CourseDetail courseDetail = courseDto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        CourseMarket courseMarket = courseDto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
    }

    /**
     * 上线
     *
     * @param courses
     */
    @Override
    public void bathUp(List<Course> courses) {
        List<CourseDoc> courseDocs = createCourseDocs(courses);
        courseDocClient.addAll(courseDocs);
//        courseMapper.bathUp(courses);
    }

    /**
     * 批量
     *
     * @param courses
     * @return
     */
    private List<CourseDoc> createCourseDocs(List<Course> courses) {
        ArrayList<CourseDoc> courseDocs = new ArrayList<>();
        for (Course cours : courses) {
            CourseDoc courseDoc = new CourseDoc();
            BeanUtils.copyProperties(cours, courseDoc);
            //查询市场
            CourseMarket courseMarket = courseMarketMapper.selectById(cours.getId());
            BeanUtils.copyProperties(courseMarket, courseDoc);
            CourseDetail courseDetail = courseDetailMapper.selectById(cours.getId());
            BeanUtils.copyProperties(courseDetail, courseDoc);
            courseDocs.add(courseDoc);
        }
        return courseDocs;
    }

    /**
     * 下线
     *
     * @param courses
     */
    @Override
    public void batchDown(List<Course> courses) {
        courseMapper.batchDown(courses);
    }

    @Override
    public CourseDetail querymarketAndDetal(Long id) {
        return courseMapper.querymarketAndDetal(id);
    }

    @Override
    public AjaxResult bathUpOrBathDown(Course course, boolean flag) {
        Course course1 = courseMapper.selectById(course);
        Date date = new Date();
        //上线
        if (flag) {
            //判断是否上线

            //添加到es
            CourseDoc courseDoc = createCourseDoc(course);
            AjaxResult ajaxResult = courseDocClient.addOrUpdate(courseDoc);
            //校验是否添加到索引库
            ValidUtils.assertBoolean(ajaxResult.isSuccess(), "添加索引失败");
            //修改数据库
            course1.setStatus(1);
            //设置上线时间
            course1.setOnlineTime(date);
            courseMapper.updateById(course1);
            //发送消息，给mq
            sendMessage(course1);

            return ajaxResult;
        } else {//下线
            //删除索引库
            AjaxResult ajaxResult = courseDocClient.deleteCourse(course1.getId());
            //校验是否从索引库删除
            ValidUtils.assertBoolean(ajaxResult.isSuccess(), "删除索引失败");
            //修改数据库
            course1.setStatus(0);
            //设置下线时间
            course1.setOfflineTime(date);
            courseMapper.updateById(course1);
            return ajaxResult;
        }
    }

    @Override
    public PageList<CourseDoc> queryCourses(CourseDocQuery courseDocQuery) {
        //通过es服务查询数据
        return courseDocClient.queryCourses(courseDocQuery);

    }

    private void sendMessage(Course course1) {
        //短信到队列
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.sms", course1.getName());
        //邮件到队列
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.email", course1.getName());
        //站内信到队列
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.system", course1.getName());
    }

    //创建Doc对象
    private CourseDoc createCourseDoc(Course course) {
        //获取课程名字
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        CourseDoc courseDoc = new CourseDoc();
        courseDoc.setCourseTypeName(courseType.getName());
        BeanUtils.copyProperties(course, courseDoc);
        //查询市场
        CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseMarket, courseDoc);
        CourseDetail courseDetail = courseDetailMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseDetail, courseDoc);
        return courseDoc;
    }


}
